import socket
import array
from Bases import setID
from Bases import OSCBaseObject

class Universe(OSCBaseObject):
    _saved_class_name = 'Universe'
    _saved_attributes = ['id', 'name', 'ola_universe_id']
    _Properties = {'name':dict(default=''), 'ola_universe_id':dict(type=int)}
    _SettingsProperties = ['name', 'ola_universe_id']
    def __init__(self, **kwargs):
        self.id = None
        self._ola_universe_id = None
        self.ola_enabled = False
        #self.comm = kwargs.get('comm')
        super(Universe, self).__init__(**kwargs)
        self.bind(ola_universe_id=self._on_ola_universe_id_set)
        self.register_signal('value_update')
        if 'deserialize' not in kwargs:
            self.id = setID(kwargs.get('id'))
            self.name = kwargs.get('name', '')
            self.ola_universe_id = kwargs.get('ola_universe_id')
        self.values = array.array('B', [0]*513)
        self.root_address = 'OSCtoOLA-%s' % (socket.gethostname())
        self.add_osc_handler(callbacks={'request-dump':self.on_osc_request_dump})
        
    def on_attribute_value_changed(self, **kwargs):
        attribute = kwargs.get('attribute')
        chan = attribute.chan
        value = int(kwargs.get('value'))
        self.values[chan-1] = value
        if self.ola_enabled:
            self.osc_node.send_message(root_address=self.root_address, client=self.root_address, 
                                       address='set-channel', value=[chan, value])
        self.emit('value_update', channel=chan, universe=self)
#        if self.dmx_io is not None:
#            self.dmx_io.sendDMXValue(values=self.values, chan=chan, univID=self.id)
        
#    @property
#    def ola_universe_id(self):
#        return self._ola_universe_id
#    @ola_universe_id.setter
#    def ola_universe_id(self, value):
#        if value is not None:
#            value = int(value)
#            address = str(value)
#            self._ola_universe_id = value
#            self.ola_enabled = True
#        else:
#            address = self.id
#            self.ola_enabled = False
#        self.set_osc_address(address)
        
    def _on_ola_universe_id_set(self, **kwargs):
        value = kwargs.get('value')
        if value is not None:
            address = str(value)
            self._ola_universe_id = value
            self.ola_enabled = True
        else:
            address = self.id
            self.ola_enabled = False
        self.set_osc_address(address)
        
    def on_osc_request_dump(self, **kwargs):
        #client = kwargs.get('client')
        self.osc_node.send_message(root_address=self.root_address, client=self.root_address, 
                                   address='dump-response', value=list(self.values))
        
#    def set_osc_address(self, value):
#        self.osc_address = value
#        self.osc_node.setName(value)
